package com.example.demo.controller;

import com.example.demo.config.MqttBroker;
import com.example.demo.entity.CodeAssociation;
import com.example.demo.entity.CodeHistory;
import com.example.demo.entity.ProductStore;
import com.example.demo.entity.UserProductinfo;
import com.example.demo.service.CodeAssociationService;
import com.example.demo.service.CodeHistoryService;
import com.example.demo.service.ProductStoreService;
import com.example.demo.service.UserProductinfoService;
import com.example.demo.util.GetMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/userproduct")
@RequiredArgsConstructor
@Component
public class UserProductInfoController {
    private final UserProductinfoService userProductinfoService;
    private final CodeHistoryService codeHistoryService;
    private final ProductStoreService productStoreService;
    private final CodeAssociationService codeAssociationService;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/select")
    public GetMessage select (String userId, Integer id){
        //String userId=token;
        UserProductinfo u=userProductinfoService.selectById(id);
        return new GetMessage("成功","200",u);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/verify")
    public GetMessage verify (String userId, String code) throws MqttException, JsonProcessingException {
        //String userId=token;
        CodeHistory codeHistory=codeHistoryService.selectByCodeInfo(code);
        UserProductinfo u=userProductinfoService.selectById((Integer) codeHistory.getProductinfoid());
        CodeAssociation codeAssociations=codeAssociationService.select(code);
        u.setCategorycode(codeAssociations.getAssociationcode());
        Map<String,Object> map=new HashMap<>();
        map.put("targetPageId","ProductInfo");
        map.put("trainingId",u.getTrainingid());
        map.put("isDisable",false);
        map.put("productInfoId",u.getId());
        map.put("data",code);
        String payload = objectMapper.writeValueAsString(map);
        MqttBroker.mqttClient.publish("SyncPage/"+u.getAppid()+"/"+userId,new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)));

        return new GetMessage("成功","200",u);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/selectproduct")
    public GetMessage selectproduct (String userId, String appId,String trainingId) throws MqttException, JsonProcessingException {
        //String userId=token;
       List<UserProductinfo>  list=userProductinfoService.selectProductInfo(userId,appId,trainingId);

        return new GetMessage("成功","200",list);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/store")
    public GetMessage store (String userId, String code) throws MqttException, JsonProcessingException {
        //String userId=token;
        CodeHistory codeHistory=codeHistoryService.selectByCodeInfo(code);
        UserProductinfo u=userProductinfoService.selectById((Integer) codeHistory.getProductinfoid());
        CodeAssociation codeAssociations=codeAssociationService.select(code);
        u.setCategorycode(codeAssociations.getAssociationcode());
        if(u==null){
            return new GetMessage("失败","500",null);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("targetPageId","PutStore");
        map.put("trainingId",u.getTrainingid());
        map.put("isDisable",false);
        map.put("productInfoId",u.getId());
        map.put("data",code);
        String payload = objectMapper.writeValueAsString(map);
        MqttBroker.mqttClient.publish("SyncPage/"+u.getAppid()+"/"+userId,new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)));

        return new GetMessage("成功","200",u);
    }

    @GetMapping("/selectetchant")
    public GetMessage selectetchant (String userId, String trainingId){
        //String userId=token;
        List<UserProductinfo> u1=userProductinfoService.selectProductInfo(userId,"etchant",trainingId);
        return new GetMessage("成功","200",u1);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/processstate")
    public GetMessage processState (Integer id) throws JsonProcessingException {
        //String userId=token;
        UserProductinfo u=userProductinfoService.selectById(id);
        List<java.util.Map<String, String>> list = objectMapper.readValue(u.getProductinfo(), objectMapper.getTypeFactory().constructCollectionType(List.class, java.util.Map.class));
        String code1="";
        String code2="";
        String name="";
        for (java.util.Map<String, String> map : list) {
            // 获取每个元素中的value字段值并添加到列表中
            if(map.get("title").equals("蚀刻机")){
                code1=userProductinfoService.selectById(Integer.parseInt(map.get("value"))).getCategorycode();
            }
            if(map.get("title").equals("蚀刻液")){
                code2=userProductinfoService.selectById(Integer.parseInt(map.get("value"))).getCategorycode();
            }
            if(map.get("title").equals("工艺名称")){
                name=map.get("value");
            }
        }
        Map<String,String> map=new HashMap<>();
        map.put("etchmachineName",name);
        map.put("etchmachineCode",code1);
        map.put("etchantCode",code2);
        map.put("etchprocessCode",u.getCategorycode());
        return new GetMessage("成功","200",map);
    }
    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/process")
    public GetMessage process (Integer id,String userId,String trainingId) throws MqttException, JsonProcessingException {
        //String userId=token;

        Map<String,Object> map=new HashMap<>();
        map.put("targetPageId","ProductState");
        map.put("trainingId",trainingId);
        map.put("isDisable",false);
        map.put("productInfoId",id);
        String payload = objectMapper.writeValueAsString(map);
        MqttBroker.mqttClient.publish("SyncPage/etchprocess/"+userId,new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)));
        return new GetMessage("成功","200",map);
    }

    @CrossOrigin(origins ="*" ,maxAge = 3600)
    @GetMapping("/proetchant")
    public GetMessage proetchant (Integer id) throws MqttException, JsonProcessingException {

        UserProductinfo userProductinfo=userProductinfoService.selectById(id);
        List<java.util.Map<String, String>> list = objectMapper.readValue(userProductinfo.getProductinfo(), objectMapper.getTypeFactory().constructCollectionType(List.class, java.util.Map.class));
        String upid = "";
        for (java.util.Map<String, String> map : list) {
            if(map.get("title").equals("蚀刻液")){
                upid=map.get("value");
            }
        }
        List<CodeHistory> list1=codeHistoryService.selectByProId(Integer.parseInt(upid));
        List<String> list2=new ArrayList<>();
        for (CodeHistory l:list1) {
            list2.add(l.getCodeinfo());
        }
        return new GetMessage("成功","200",list2);
    }

//    @CrossOrigin(origins ="*" ,maxAge = 3600)
//    @GetMapping("/getregister")
//    public GetMessage getRegister (String userId,String trainingId){
//        //String userId=token;
//        Map<String,Object> map=new HashMap<>();
//        List<UserProductinfo> u1=userProductinfoService.selectProductInfo(userId,"etchant",trainingId);
//        List<ProductStore> u2=productStoreService.selectByInfo(userId,"etchant",trainingId);
//        List<UserProductinfo> list=new ArrayList<>();
//        for (UserProductinfo elementU1 : u1) {
//            for (ProductStore elementU2 : u2) {
//                if (elementU1.getId() .equals(elementU2.getUserproductinfoid()) ) {
//                    list.add(elementU1);
//                }
//            }
//        }
//        List<UserProductinfo> u3=userProductinfoService.selectProductInfo(userId,"etchmachine",trainingId);
//        List<UserProductinfo> u4=userProductinfoService.selectProductInfo(userId,"pcbproducts",trainingId);
//        map.put("etchant",list);
//        map.put("etchmachine",u3);
//        map.put("pcbproducts",u4);
//        return new GetMessage("成功","200",map);
//    }
}
